package pers.vic.boot.base.tool;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 系统级别的工具类
 * 
 * @author VIC
 *
 */
public class Tools {
	

	/**
	 * 获得当前线程中的request
	 * 
	 * @exception 当前线程中不存在
	 *                Request 上下文
	 */
	public static HttpServletRequest currentRequest() {
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attr == null) {
			throw new IllegalStateException("当前线程中不存在 Request 上下文");
		}
		return attr.getRequest();
	}

	/**
	 * 获得当前线程中的session 不存在则返回null
	 * 
	 * @return
	 */
	public static HttpSession currentSession() {
		ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		if (attr == null) {
			return null;
		}
		return attr.getRequest().getSession(false);
	}

	static ObjectMapper objectMapper = new ObjectMapper();
	/**
	 * 通过response输出JSON
	 * 
	 * @return
	 */
	public static void writeJson(Object obj, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(objectMapper.writeValueAsString(obj));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	/** 获得当前请求的URL */
	public static String getRequestUrl(HttpServletRequest request) {
		String contextPath = request.getContextPath();
		String requestURI = request.getRequestURI();
		int i = requestURI.indexOf("?");
		if (i < 0) {
			i = requestURI.length();
		}
		return requestURI.substring(contextPath.length(), i);
	}
	

	
	
}
